/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.search.web.KeywordAction
   Module Description   :

   Date Created      : 2010/3/1
   Original Author   : jeff.ma
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.search.web;

import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.template.service.TemplateService;
import com.yaodian100.ec.category.entity.Category;
import com.yaodian100.ec.category.service.CategoryService;
import com.yaodian100.ec.common.web.AbstractAction;
import com.yaodian100.ec.generate.service.GenerateService;
import com.yaodian100.ec.search.entity.Keyword;
import com.yaodian100.ec.search.entity.KeywordDefault;
import com.yaodian100.ec.search.service.KeywordService;

/**
 * @author jeff.ma
 * 
 */
public class KeywordAction extends AbstractAction {

	public class CategoryCompare implements Comparator<Category> {

		/** default constructor */
		public CategoryCompare() {
			super();
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
		 */
		@Override
		public int compare(Category o1, Category o2) {
			if (o1 != null && o2 != null) {
				return (o2.getShowSeq() - o1.getShowSeq());
			} else {
				return -1;
			}
		}
	}

	/** serialVersionUID */
	private static final long serialVersionUID = 5892183752642618860L;
	@Autowired
	private KeywordService keywordService;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private GenerateService generateService;

	@Autowired
	private TemplateService templateService;

	/* menu */
	private List<Category> categories;
	/* 由FORM传入之查询条件 */
	private String paramId;
	private String paramPath;

	private String paramLevel;
	private Keyword keyword;
	private String uuid;
	private List<Keyword> keywordList;
	private String word;

	/**
	 * @return the word
	 */
	public String getWord() {
		return word;
	}

	/**
	 * @param word the word to set
	 */
	public void setWord(String word) {
		this.word = word;
	}

	private Category category;

	/** default constructor */
	public KeywordAction() {
	}

	/**
	 * 載入新增物件資料頁
	 * 
	 * @return
	 */
	public String add() {
		keyword = new Keyword();
		return "edit";
	}

	public String delete() throws Exception {
		try {
			keyword = (Keyword) baseMgr.get(Keyword.class, paramId);
			if (keyword == null) {
				addActionError("物件不存在");
				return search();
			}
			if (keyword.getCategoryId().longValue() == 0) {
				addActionError("首頁 Keyword 不可刪除");
				return "view";
			}
			keywordService.delete(keyword);

			String pathId = keyword.getCategoryId().toString();
			File file = new File(ServerValue.getFrontContentHtmlPath() + File.separator + pathId + File.separator
					+ "SEARCHBAR.html");
			file.deleteOnExit();

			File fileV2 = new File(ServerValue.getFrontContentHtmlPath() + File.separator + pathId + File.separator
					+ "SEARCHBAR_V2.html");
			fileV2.deleteOnExit();

		} catch (Exception e) {
			addActionError("删除失败：" + e.getMessage());
			e.printStackTrace();
			return "view";
		}
		return search();
	}

	/**
	 * 修改物件資料
	 * 
	 * @return
	 * @throws Exception
	 */
	public String edit() throws Exception {
		keyword = (Keyword) baseMgr.get(Keyword.class, paramId);
		if (keyword == null) {
			addActionError("物件不存在, 重新选取");
			return search();
		}
		return "edit";
	}

	/**
	 * @return the categories
	 */
	public List<Category> getCategories() {
		return categories;
	}

	/**
	 * @return the category
	 */
	public Category getCategory() {
		return category;
	}

	/**
	 * @return the keyword
	 */
	public Keyword getKeyword() {
		return keyword;
	}

	/**
	 * @return the keywordList
	 */
	public List<Keyword> getKeywordList() {
		return keywordList;
	}

	/**
	 * @return the categoryId
	 */
	public String getParamId() {
		return paramId;
	}

	/**
	 * @return the categoryLevel
	 */
	public String getParamLevel() {
		return paramLevel;
	}

	/**
	 * @return the categoryPath
	 */
	public String getParamPath() {
		return paramPath;
	}

	/**
	 * @return the uuid
	 */
	public String getUuid() {
		return uuid;
	}

	public String list() throws Exception {
		return "list";
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.common.web.AbstractAction#prepare()
	 */
	@Override
	public void prepare() throws Exception {
		clearErrorsAndMessages();
		if (categories == null) {
			Category root = new Category();
			root.setId(0L);
			root.setName("全站");
			categories = new ArrayList<Category>();
			categories.add(0, root);
			List<Category> parents = categoryService.getChild(0l);
			categories.addAll(parents);
			for (Category parent : parents) {
				categories.addAll(categoryService.getAvailableChild(parent.getId()));
			}
		}
		super.prepare();
	}

	/**
	 * 储存物件资料
	 * 
	 * @return
	 * @throws Exception
	 */
	public String save() throws Exception {
		try {
			if (paramId != null && !paramId.equals("")) {
				keyword = (Keyword) baseMgr.get(Keyword.class, paramId);
				keyword.setWord(word);
			} else {
				keyword = new Keyword();
				keyword.setWord(word);
				keyword.setCategoryId(Long.parseLong(categoryId));
				List<Keyword> tmp = keywordService.getList(0, 1, new CommonCriteria().addEq("categoryId", keyword
						.getCategoryId()), null);
				if (tmp.size() > 0) {
					addActionError("目录已经建立关键字, 请重新设定目录, 或以搜寻选取改目录");
					return "edit";
				}

				category = categoryService.get(keyword.getCategoryId());
				if (category != null) {
					keyword.setCategoryLevel(category.getLevel());
					keyword.setCategoryPath(category.getCategoryPath());
				}
			}
			if (keyword != null) {

				keyword = keywordService.save(keyword);
				generateService.generateSearchbar_V2(keyword.getCategoryId().toString());
			} else {
				addActionError("物件不存在");
				return search();
			}
		} catch (Exception e) {
			addActionError("储存失败：" + e.getMessage());
			e.printStackTrace();
			return "edit";
		}
		return "view";
	}

	public String search() throws Exception {
		try {
			CommonCriteria cri = new CommonCriteria();
			if (StringUtils.isNotBlank(paramId)) {
				cri.addEq("categoryId", Long.valueOf(paramId));
			}
			if (StringUtils.isNotBlank(paramPath)) {
				cri.addRlike("categoryPath", paramPath);
			}
			if (StringUtils.isNotBlank(paramLevel)) {
				cri.addEq("categoryLevel", paramLevel);
			}

			int entitySize = keywordService.getListSize(cri).intValue();
			getPager().setTotalSize(entitySize);
			keywordList = keywordService.getList(getPager().getCurrentPage() * getPager().getPageRecord(), getPager()
					.getPageRecord(), cri, new String[] { "categoryPath asc" });
		} catch (Exception e) {
			addActionError("搜寻失败：" + e.getMessage());
			e.printStackTrace();
		}
		return "list";
	}

	/**
	 * @param categoryId the categoryId to set
	 */
	public void setParamId(String categoryId) {
		this.paramId = categoryId;
	}

	/**
	 * @param categoryLevel the categoryLevel to set
	 */
	public void setParamLevel(String categoryLevel) {
		this.paramLevel = categoryLevel;
	}

	/**
	 * @param categoryPath the categoryPath to set
	 */
	public void setParamPath(String categoryPath) {
		this.paramPath = categoryPath;
	}

	/**
	 * @param uuid the uuid to set
	 */
	public void setUuid(String uuid) {
		this.uuid = uuid;
	}

	/**
	 * 檢視物件資料
	 * 
	 * @return
	 */
	public String view() throws Exception {
		if (StringUtils.isNotBlank(uuid)) {
			keyword = keywordService.get(uuid);
		}
		if (keyword == null) {
			addActionError("物件UUID 有误, 重新选取");
			return search();
		}
		if (keyword.getCategoryId().longValue() != 0) {
			category = categoryService.get(Long.valueOf(keyword.getCategoryId()));
		}
		return "view";
	}

	@Resource
	private BaseManager baseMgr;
	private String categoryId;
	private String keywordStr;
	private String defId;
	private String message;

	/**
	 * @return the message
	 */
	public String getMessage() {
		return message;
	}

	/**
	 * @param message the message to set
	 */
	public void setMessage(String message) {
		this.message = message;
	}

	/**
	 * @return the defId
	 */
	public String getDefId() {
		return defId;
	}

	/**
	 * @param defId the defId to set
	 */
	public void setDefId(String defId) {
		this.defId = defId;
	}

	/**
	 * @return the keywordStr
	 */
	public String getKeywordStr() {
		return keywordStr;
	}

	/**
	 * @param keywordStr the keywordStr to set
	 */
	public void setKeywordStr(String keywordStr) {
		this.keywordStr = keywordStr;
	}

	/**
	 * @return the categoryId
	 */
	public String getCategoryId() {
		return categoryId;
	}

	/**
	 * @param categoryId the categoryId to set
	 */
	public void setCategoryId(String categoryId) {
		this.categoryId = categoryId;
	}

	public String deleteDefaultKeyword() {
		if (defId != null && defId.length() > 0) {
			baseMgr.delete(baseMgr.load(KeywordDefault.class, defId));
		}
		return "listDK";
	}

	public String toUpdateDefaultKeyword() {
		return "updateDK";
	}

	public String updateDefaultKeyword() {
		KeywordDefault kd = null;
		message = "default";
		try {
			if (paramId != null && paramId.length() > 0) {
				kd = (KeywordDefault) baseMgr.get(KeywordDefault.class, paramId);
				kd.setCategoryId(Long.valueOf(categoryId));
				kd.setKeyword(keywordStr);
				baseMgr.update(kd);
				message = "已完成修改";
			} else {
				kd = new KeywordDefault();
				kd.setCategoryId(Long.valueOf(categoryId));
				kd.setKeyword(keywordStr);
				baseMgr.save(kd);
				message = "已完成新增";
			}
			generateService.generateSearchbar_V2(categoryId.toString());
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);

		}
		return "updateDK";
	}

	public String listDefaultKeyword() {
		return "listDK";
	}
}
